/*
Copyright 2007 Nathan Baker

This file is part of XAliens.

XAliens is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

XAliens is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with XAliens.  If not, see <http://www.gnu.org/licenses/>.
 */

package utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;

public class SpriteMap {
    HashMap<String, BufferedImage> images;

    /**
     * Creates a default SpriteMap.
     */
    public SpriteMap() {
        images = new HashMap<String, BufferedImage>();
    }

    /**
     * Use this method to get an image from the SpriteMaps list of stored
     * images. If the image has been requested previously a reference to the
     * existing image is returned. Otherwise the SpriteMap attempts to load the
     * image from the local filesystem. A relative filepath can be used. e.g.
     * "../images/blah.gif"
     *
     * @param path The path to load the image from.
     * @param scr
     * @return An image.
     */
    public BufferedImage getImage(String path, Graphics2D scr) throws Exception {
        BufferedImage img = images.get(path);

        //TODO: set the colormodel of img
        if (img == null) {
            URL url = this.getClass().getClassLoader().getResource(path);
            try {
                BufferedImage bimg = ImageIO.read(url);
                if (bimg == null) {
                    throw new FileNotFoundException(url.toString());
                }
                //Graphics2D g2 = bimg.createGraphics();
                //AlphaComposite alphaComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER);
                //g2.setComposite(alphaComposite);

                images.put(path, bimg);
                img = images.get(path);
            } catch (IOException e) {
                System.err.print("IO exception: "
                        + e.getMessage() + "\nPath: " + path);
                throw e;
            } catch (IllegalArgumentException e) {
                System.err
                        .print("IllegalArgumentException: "
                                + e.getMessage() + "\nPath: " + path);
                throw e;
            } catch (Exception e) {
                System.err.print("Exception ocurred: "
                        + e.getMessage());
                throw e;
            }
        }

        return img;
    }
}
